<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理员列表</title>
    <link rel="stylesheet" type="text/css" th:href="@{/manager/easyui/themes/default/easyui.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/manager/easyui/themes/icon.css}">
    <script type="text/javascript" th:src="@{/manager/easyui/jquery.min.js}"></script>
    <script type="text/javascript" th:src="@{/manager/easyui/jquery.easyui.min.js}"></script>
	<script type="text/javascript">
	    //工具栏
	    var toolbar = [{
	        text: '新增',
	        iconCls: 'icon-add',
	        handler: function () {
                uncheckAllTreeCheckboxes($("#bh"));
                $("#ad input.easyui-textbox:eq(0)").textbox("setValue","");
                $("#ad input.easyui-textbox:eq(1)").textbox("setValue","");
                $("#companylist").combobox("setValue", "-1");
                $('#ad').dialog('open');
            }
	    }, '-',{
	        text: '修改',
	        iconCls: 'icon-edit',
	        handler: function () {
                uncheckAllTreeCheckboxes($("#ah"));
                var selectedRow = $("#userlist").datagrid('getSelected');
                if(selectedRow) {
                    $.ajax({
                        dataType: "json",
                        url: "/manager/manageruser/findById",
                        data: {
                            "id": selectedRow.id
                        },
                        success: function (result) {
                            if (result.status == 200) {
                                $("#dd input.easyui-textbox:eq(0)").textbox("setValue",result.data.id);
                                $("#dd input.easyui-textbox:eq(1)").textbox("setValue",result.data.password);
                                $("#dd input.easyui-textbox:eq(2)").textbox("setValue",result.data.username);
                                if(result.data.commpanyid == null){
                                    $("#commpanylist").combobox("setValue", "0");
                                }else{
                                    $("#commpanylist").combobox("setValue", result.data.commpanyid.toString());
                                }
                                result.data.roles[0].roles.forEach(function (role) {
                                    var node = $("#ah").tree('find', role.id);
                                    $("#ah").tree('check', node.target);
                                });
                                $('#dd').dialog('open');
                            }
                        },
                        error: function (xhr, status, error) {
                            alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                        }
                    });
                }else{
                    alert("请选中列表中对应的信息!");
                }
            }
	    }];

        //取消所有勾选以及选中的行，折叠所有选项
        function uncheckAllTreeCheckboxes(treeObject) {
            var rootNodes = treeObject.tree('getRoots');
            for ( var i = 0; i < rootNodes.length; i++) {
                var node = treeObject.tree('find', rootNodes[i].id);
                treeObject.tree('uncheck', node.target);
            }
            treeObject.tree('collapseAll');
            treeObject.find('.tree-node-selected').removeClass('tree-node-selected');
        }

        function hasAnyCheckedNodes(treeNode) {
            var nodes = treeNode.tree('getChecked', ['checked']); // 只获取 checked 状态的节点
            return nodes.length > 0; // 如果有节点被勾选，返回 true；否则返回 false
        }

        function getAllCheckedAndIndeterminateNodeIds(treeNode) {
            var checkedAndIndeterminateNodes = treeNode.tree('getChecked', ['checked', 'indeterminate']);
            var nodeIds = [];
            // 遍历所有被勾选和部分勾选的节点，并将它们的 ID 添加到 nodeIds 数组中
            $.each(checkedAndIndeterminateNodes, function(index, node){
                nodeIds.push(node.id);
            });
            return nodeIds;
        }

	   $(function(){
	       $('#userlist').datagrid({  
			title:'管理员列表',  
			iconCls:'icon-save',
            queryParams:{
                "name": null
            },
            url:"/manager/manageruser/findAll",
			columns:[
                [
				{field:'id',title:'管理员ID',width:100,align:'center'},  
				{field:'username',title:'管理员名称',width:100,align:'center'},
				{field:'password',title:'管理员密码',width:100,align:'center'},  
				{field:'roles',title:'拥有的角色',width:200,align:'center',formatter:function (val,row) {
                        var rolesStr = "<select name='search_type' style='width:100%'>";
                        if (val[0].roles && val[0].roles.length > 0) {
                            val[0].roles.forEach(function (role) {
                                rolesStr += '<option>' + role.name + '</option>';
                            });
                            rolesStr += "</select>";
                        } else {
                            rolesStr = '无角色';
                        }
                        return rolesStr;
                    }}
			]
            ],
            singleSelect:true,
			pagination:true,
			toolbar: toolbar  
		});
		 //初始化查询栏
		 $("#submit_search").linkbutton({ iconCls: 'icon-search', plain: true })
            .click(function () {
                const tooldiv = document.getElementById('searchform');
                const inputs = tooldiv.querySelectorAll('input[type="text"]');
                var pager = $('#userlist').datagrid('getPager');
                // 直接设置数据网格的查询参数
                var queryParams = {
                    "page": 1,
                    "name": inputs[0].value
                };
                $('#userlist').datagrid('options').queryParams = queryParams;
                $('#userlist').datagrid('reload');
                pager.pagination('refresh', {
                    pageNumber: 1
                });
            });

           //初始化新增窗口
           $('#ad').dialog({
               title: 'My Dialog',
               width: 700,
               height: 500,
               closed: true,
               cache: false,
               href: '',
               modal: true,
               iconCls: 'icon-save',
               buttons: [{
                   text:'提交',
                   iconCls:'icon-ok',
                   handler:function(){
                       if ($('#ad input[name="name"]').eq(0).val().trim() === "" || $('#ad input[name="name"]').eq(1).val().trim() === "" || $("#companylist").combobox("getValue") === "-1" || !hasAnyCheckedNodes($('#bh'))) {
                           alert("管理员密码内容或管理员名称内容或服务商内容或角色内容不能为空!");
                       }else {
                           $.ajax({
                               type: 'post',
                               dataType: "json",
                               url: "/manager/manageruser/add",
                               data: {
                                   "password": $("#ad input.easyui-textbox:eq(0)").textbox("getValue"),
                                   "name": $("#ad input.easyui-textbox:eq(1)").textbox("getValue"),
                                   "id": $("#companylist").combobox("getValue"),
                                   "ids" : getAllCheckedAndIndeterminateNodeIds($('#bh')).toString()
                               },
                               success: function (result) {
                                   if (result.status == 200) {
                                       alert(result.msg);
                                       $('#userlist').datagrid('reload');
                                       $('#ad').dialog('close');
                                   }
                               },
                               error: function (xhr, status, error) {
                                   alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                               }
                           });
                       }
                   }
               },{
                   text:'关闭',
                   handler:function(){
                       $('#ad').dialog('close');
                   }
               }]
           });

          //初始化修改窗口  
         $('#dd').dialog({
			    title: 'My Dialog',
			    width: 700,
			    height: 500,
			    closed: true,
			    cache: false,
			    href: '',
			    modal: true,
			    iconCls: 'icon-save',
                buttons: [{
                    text:'提交',
                    iconCls:'icon-ok',
                    handler:function(){
                        if ($('#dd input[name="name"]').eq(1).val().trim() === "" || $('#dd input[name="name"]').eq(2).val().trim() === "" || $("#commpanylist").combobox("getValue") === "-1" || !hasAnyCheckedNodes($('#ah'))) {
                            alert("管理员密码内容或管理员名称内容或服务商内容或角色内容不能为空!");
                        }else {
                            $.ajax({
                                type: 'post',
                                dataType: "json",
                                url: "/manager/manageruser/modify",
                                data: {
                                    "password": $("#dd input.easyui-textbox:eq(1)").textbox("getValue"),
                                    "name": $("#dd input.easyui-textbox:eq(2)").textbox("getValue"),
                                    "companyid" : $("#commpanylist").combobox("getValue"),
                                    "ids" : getAllCheckedAndIndeterminateNodeIds($('#ah')).toString(),
                                    "id" : $("#dd input.easyui-textbox:eq(0)").textbox("getValue")
                                },
                                success: function (result) {
                                    if (result.status == 200) {
                                        alert(result.msg);
                                        var selectedRow = $("#userlist").datagrid('getSelected');
                                        var index = $("#userlist").datagrid('getRowIndex', selectedRow);
                                        $.ajax({
                                            dataType: "json",
                                            url: "/manager/manageruser/findRoles",
                                            data: {
                                                "id": selectedRow.id
                                            },
                                            success: function (result) {
                                                if (result.status == 200) {
                                                    $("#userlist").datagrid('updateRow', {
                                                        index: index,
                                                        row: {
                                                            username: $("#dd input.easyui-textbox:eq(2)").textbox("getValue"),
                                                            password: $("#dd input.easyui-textbox:eq(1)").textbox("getValue"),
                                                            roles: result.data.roles
                                                        }
                                                    });
                                                }
                                            },
                                            error: function (xhr, status, error) {
                                                alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                                            }
                                        });
                                        $('#dd').dialog('close');
                                    }
                                },
                                error: function (xhr, status, error) {
                                    alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                                }
                            });
                        }
                    }
                },{
                    text:'关闭',
                    handler:function(){
                        $('#dd').dialog('close');
                    }
                }]
			});

           function initializeTree(node) {
               $.ajax({
                   url: '/manager/role/findRoles', // 替换为你的后端数据接口
                   type: 'GET',
                   dataType: 'json', // 假设后端返回JSON格式数据
                   success: function(result) {
                       // 假设data已经是你需要的树形结构，直接初始化树形控件
                       node.tree({
                           data: result.data,
                           method: 'post',
                           animate: true,
                           checkbox: true
                       });
                   },
                   error: function(xhr, status, error) {
                       alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                   }
               });
           }

           function initializeServerCompany(list) {
               $.ajax({
                   url: '/manager/serverCompany/findCompanies', // 替换为你的后端数据接口
                   type: 'GET',
                   dataType: 'json', // 假设后端返回JSON格式数据
                   success: function(result) {
                       if(result.status == 200){
                           list.combobox({
                               data:result.data,
                               width:300,
                               label:"服务商:",
                               valueField:'id',
                               textField:'text'
                           });
                       }
                   },
                   error: function(xhr, status, error) {
                       alert("请求失败: " + xhr.responseText); // 处理 AJAX 请求错误
                   }
               });
           }

           // 调用函数初始化服务商列表
           initializeServerCompany($("#companylist"))
           // 调用函数初始化服务商列表
           initializeServerCompany($("#commpanylist"))
           // 调用函数初始化树形控件
           initializeTree($("#bh"));
           // 调用函数初始化树形控件
           initializeTree($("#ah"));
	   });

	</script>
</head>
<body>
   <form name="searchform" method="post" action="" id ="searchform">
    <td width="70" height="30"><strong>管理员查询：</strong></td>
    <td height="30">
        <input type="text" name="keyword" size=20 placeholder="管理员名称"/>
        <a id="submit_search">搜索</a>
    </td>
  </form>
  <table id="userlist"></table>
    <div id="dd">
           <div align="center" style="margin-top: 30px">
            <form id="ff" method="post">
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="name" style="width:50%" data-options="label:'管理员ID:'" readonly="readonly"/>
            </div>
             <div style="margin-bottom:20px">
                <input class="easyui-textbox" type="password" name="name" style="width:50%" data-options="label:'管理员密码:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="name" style="width:50%" data-options="label:'管理员名称:',required:true">
            </div>
			 <div style="margin-bottom:20px">
               <select id="commpanylist"></select>
            </div>
            <div style="margin-bottom:20px">
                  <table style="width:48%">
                    <td valign="top" style="width:50px">
                     角色:
                    </td>
                    <td><ul id="ah"></ul></td>
                  </table>
            </div>
        </form>
        </div>
    </div>
   <div id="ad">
       <div align="center" style="margin-top: 30px">
           <form id="af" method="post">
               <div style="margin-bottom:20px">
                   <input class="easyui-textbox" type="password" name="name" style="width:50%" data-options="label:'管理员密码:',required:true">
               </div>
               <div style="margin-bottom:20px">
                   <input class="easyui-textbox" name="name" style="width:50%" data-options="label:'管理员名称:',required:true">
               </div>
               <div style="margin-bottom:20px">
                   <select id="companylist"></select>
               </div>
               <div style="margin-bottom:20px">
                   <table style="width:48%">
                       <td valign="top" style="width:50px">
                           角色:
                       </td>
                       <td><ul id="bh"></ul></td>
                   </table>
               </div>
           </form>
       </div>
   </div>
</body>
</html>